//
//  HMStatusViewModel.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/9/24.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import YYText
//专门为首页自定义cell服务
class HMStatusViewModel: NSObject {

    //首页数据模型对象
    var status = HMStatus()
    //会员等级图片
    var mbrankImage:UIImage?
    //转发数
    var retweetCount:String?
    //评论数
    var commentcount:String?
    //赞数量
    var unlikecount:String?
    //转发微博
    var retweetContent:String?
    //认证类型图片
    var verifiedTypeImage:UIImage?
    //来源
    var sourceContent:String?
    //微博时间
    var timeContent:String? {
        guard let createAt = status.created_at else {
            return nil
        }
        
//        //执行到此说明时间字符串不为空
//        let dt = DateFormatter()
//        //指定格式化方式
//        dt.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
//        //指定本地化信息
//        dt.locale = Locale(identifier:"en_US")
//        //把字符串转换成时间对象
//        let createAtDate = dt.date(from: createAt)
        //print(createAtDate)
        return Date.sinaDate(createAt:createAt).sinaDateString
        
//        if isThisYear(createAtDate: createAtDate!) {
//            print("是今年")
//            //获取日历对象
//            let currentCalender = Calendar.current
//            //判断发微博时间是否是今天，如果是今天就判断分钟和小时
//            if currentCalender.isDateInToday(createAtDate!) {
//                let timeInterVal:TimeInterval = abs((createAtDate?.timeIntervalSinceNow)!)
//                if timeInterVal < 60 {
//                    //如果小于60秒
//                    return "刚刚"
//                }else if timeInterVal < 3600 {
//                    //如果小于一小时
//                    //得到分钟数
//                    let result = timeInterVal / 60
//                    return "\(result)分钟前"
//                }else {
//                    //得到小时数
//                    let result = timeInterVal / 3600
//                    return "\(result)小时前"
//                    
//                }
//                
//            }else if currentCalender.isDateInYesterday(createAtDate!) {
//                //如果是昨天
//                dt.dateFormat = "昨天 HH:mm"
//            }else {
//                //其他时间
//                dt.dateFormat = "MM-dd HH:mm"
//            }
//            
//        }else{
//            print("不是今年")
//            dt.dateFormat = "yyyy-MM-dd HH:mm"
//        }
//        
//        return dt.string(from: createAtDate!)
    }
    
    //原创微博富文本
    var originalAttributedString:NSAttributedString?
    
    //转发微博富文本
    var retweetAtrributedString:NSAttributedString?
    
    
    init(status:HMStatus) {
        super.init()
        self.status = status
        
        handleMBrankImage(mbrank: status.user?.mbrank ?? 0)
        
       retweetCount = handleCount(count: status.reposts_count, defaultTitle: "转发")
       commentcount = handleCount(count: status.comments_count, defaultTitle: "评论")
       unlikecount = handleCount(count: status.attitudes_count, defaultTitle: "赞")
        
        handleRetweetContent(status: status)
        handleVerifiedTypeImage(verifiedType: status.user?.verified_type ?? 0)
        handleSourceContent(source: status.source ?? "")
        //处理原创微博的数据
        originalAttributedString = handleStatusAttributedString(status: status.text!,isRetweet: false)
    }
    
    //匹配高亮文字范围
    
    
    //添加高亮效果的方法
    private func addHighlightedAttributedString(regular:String,resultAttributedString:NSMutableAttributedString) {
        
        //获取富文本对应的字符串
        let text = resultAttributedString.string
        //使用正则匹配高亮文字
        let matchHighlightedResult = try!NSRegularExpression(pattern: regular, options: []).matches(in: text, options: [], range: NSMakeRange(0, (text as NSString).length))
        //遍历匹配的结果
        for matchHighlighted in matchHighlightedResult {
            //获取高亮匹配的范围
            let range = matchHighlighted.range
            //设置高亮内容的字体颜色
            let color = UIColor(red: 80 / 255, green: 125 / 255, blue: 215 / 255, alpha: 1)
            resultAttributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
            //创建高亮富文本对象
            let textHighlight = YYTextHighlight()
            //设置高亮内容的点击颜色
            let bgColor = UIColor(red: 177 / 255, green: 215 / 255, blue: 255 / 255, alpha: 1)
            let border = YYTextBorder(fill: bgColor, cornerRadius: 3)
            //设置border内间距
            border.insets = UIEdgeInsets(top: 1, left: 0, bottom: 0, right: 0)
            textHighlight.setBackgroundBorder(border)
            //设置高亮效果
            resultAttributedString.yy_setTextHighlight(textHighlight, range: range)
            
            
            
        }
        
    }
    
    //根据正则匹配表情描述字符串转成富文本
    private func handleStatusAttributedString(status:String,isRetweet:Bool)-> NSAttributedString {
        //先把微博字符串转成富文本
        let resultAttributedString = NSMutableAttributedString(string: status)
        //根据正则匹配字符串
        let matchResult = try!NSRegularExpression(pattern: "\\[\\w+\\]", options: []).matches(in: status, options: [], range: NSMakeRange(0, (status as NSString).length))
        
        for match in matchResult.reversed() {
            let range = match.range
            let chs = (status as NSString).substring(with: range)
            //print(chs)
            //通过表情描述查找表情模型
            if let emoticon = HMEmoticonTools.sharedTools.selectedEmoticon(chs: chs){
                //print(emoticon.png)
                //根据表情模型里面的图片路径创建对应的富文本
//                let attributedStr = NSAttributedString.attributedStringWithEmoticon(emoticon: emoticon, font: UIFont.systemFont(ofSize: 14))
                //根据路径创建UIImage对象
                let image = UIImage(named: emoticon.path!)
                
                //使用YYText创建表情富文本
                let attributedStr = NSAttributedString.yy_attachmentString(withEmojiImage: image!, fontSize: 14)
                
                //根据指定范围替换成表情富文本
                resultAttributedString.replaceCharacters(in: range, with: attributedStr!)
                
            }
            
        }
        //设置全部富文本的字体大小
        resultAttributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(0, resultAttributedString.length))
        
        
        //设置原创微博和转发微博的富文本字体颜色
        if isRetweet {
            //代表转发微博
            resultAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGray, range: NSMakeRange(0, resultAttributedString.length))
            
        }else{
            //代表原创微博
            resultAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGray, range: NSMakeRange(0, resultAttributedString.length))
        }
        
        addHighlightedAttributedString(regular: "@\\w+", resultAttributedString: resultAttributedString)
        
        addHighlightedAttributedString(regular: "#[^#]+#", resultAttributedString: resultAttributedString)
        
        addHighlightedAttributedString(regular: "http[s]?://[^\\s\\u4e00-\\u9fa5]+", resultAttributedString: resultAttributedString)
        
        return resultAttributedString
    }
    
    //根据时间对象判断是否是今年
//    private func isThisYear(createAtDate:Date) -> Bool {
//        let dt = DateFormatter()
//        //指定格式化方式
//        dt.dateFormat = "yyyy"
//        //指定本地化信息
//        dt.locale = Locale(identifier:"en_US")
//        //获取发微博时间的年份
//        let createAtYear = dt.string(from: createAtDate)
//        //获取当前时间的年份
//        let currentDateYear = dt.string(from: Date())
//        //判断时间年份是否相同
//        return createAtYear == currentDateYear
        
        
//    }
    
    //处理来源数据
    fileprivate func handleSourceContent(source:String) {
        //判断字符串中是否有包含特定字符串
        if source.contains(">") && source.contains("</") {
            //截取指定范围的字符串
            let startRange = source.range(of: ">")
            let endRange = source.range(of: "</")
            //光标的起点
            let startIndex = startRange?.upperBound
            
            //光标的终点
            let endIndex = endRange?.lowerBound
            //截取子串
            sourceContent = "来自: " + source.substring(with: startIndex!..<endIndex!)
            
        }
    }
    
    //处理认证类型等级图片
    //认证类型等级 -1：没有认证，1，认证用户，2,3,5: 企业认证，220: 达人
    private func handleVerifiedTypeImage(verifiedType:Int) {
        switch verifiedType {
        case 1:
            verifiedTypeImage = UIImage(named:"avatar_vip")
        case 2,3,5:
            verifiedTypeImage = UIImage(named:"avatar_enterprise_vip")
        case 220:
            verifiedTypeImage = UIImage(named:"avatar_grassroot")
            default:
            verifiedTypeImage = nil
        }
    }
    
    //判断会员等级
    private func handleMBrankImage(mbrank:Int) {
        //判断数据是否在1-6之间
        if mbrank >= 1 && mbrank <= 6 {
            mbrankImage = UIImage(named:"common_icon_membership_level\(mbrank)")
        }
    }
    
    //处理转发，评论，赞的数量问题
    private func handleCount(count:Int,defaultTitle:String)->String {
        if count > 0 {
            return "\(count)"
        }else{
            return defaultTitle
        }
    }
    
    //处理转发微博
    private func handleRetweetContent(status:HMStatus) {
        if status.retweeted_status != nil {
            //获取转发微博的用户名
            let name = status.retweeted_status
            //获取转发微博的内容
            let text = status.retweeted_status?.text
            
            if name != nil && text != nil {
                //用户名和内容做拼接
                retweetContent = "@\(name):\(text)"
            }
            
            //处理转发微博的富文本
            retweetAtrributedString = handleStatusAttributedString(status: retweetContent!,isRetweet: true)
        }
    }
}
